﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using CrazyTalk.BLL;
using CrazyTalk.Common;
using CrazyTalk.Config;
using CrazyTalk.Models;
using CrazyTalk.Models.EnumList;
namespace CrazyTalk.Web.UI
{
    public class UserPage : PageBase
    {
        private bool _isMasterPage = true;
        /// <summary>
        /// 当前页面页面是否为继承母版页的页面
        /// </summary>
        public bool IsMasterPage { get { return _isMasterPage; } set { _isMasterPage = value; } }
        /// <summary>
        /// 当前用户信息
        /// </summary>
        public UserInfo CurUserInfo { get; set; }
        /// <summary>
        /// 适配用户账号
        /// 此账号的操作可以等同的账号
        /// 比如子账号等同父级账号
        /// 可以在查询权限等进行等同处理
        /// 但是具体编辑人,日志记录不可以使用等同.
        /// </summary>
        public string AdaptUserId { get; set; }
        /// <summary>
        /// 适配角色
        /// </summary>
        public int AdaptRoleId { get; set; }
        public UserPage()
        {
            /**/
            if (!IsLogin())
            {
                //AlertAndGo("登陆状态无效，请重新登陆", PageHelper.RootUrl + ("/Login.aspx"));                
                HttpContext current = HttpContext.Current;
                //current.Response.Write(string.Format("<script>alert('{0}');window.top.location.href='{1}'</script>", "登录状态无效，请重新登录", PageHelper.RootUrl + "/Login.aspx"));
                //current.Response.Write(string.Format("<html><head><link href=\"/css/mo/dialog.css\" rel=\"stylesheet\" type=\"text/css\" /><script type=\"text/javascript\" src=\"/js/jquery.js\"></script><script src=\"/js/mo.ui.js\" type=\"text/javascript\"></script></head><body><script>Message(\"info\", '<div class=\"s\"></div><div class=\"c\">' + 'data.message' + '</div><div class=\"e\"></div>', 5, {{ \"unique\": \"message\", \"center\": true }});window.top.location.href='{0}'</script></body></html>", PageHelper.RootUrl + "/Login.aspx"));
                //MessageBox_On_The_Lower_Depths("info", "登录状态已过期，请重新登录", "/index.html", 2);
                //current.Response.Write(string.Format("<script>window.location.href='{0}'</script>", PageHelper.RootUrl + "/Index.aspx"));
                current.Response.Write(JSON.GetJsonMessage(false, "登录状态已过期，请重新登录","login"));
                current.Response.End();
                return;
            }
            HttpCookie cookie = HttpContext.Current.Request.Cookies["CrazyTalk_tg"];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddMinutes(ConfigHelper.GetConfigInt(Consts.LoginExpiredTime));
                HttpContext.Current.Response.SetCookie(cookie);
            }
        }
        #region 输出页面前的处理
        /*
        protected override void Render(HtmlTextWriter writer)
        {
            TextWriter tempWriter = new StringWriter();
            base.Render(new HtmlTextWriter(tempWriter));
            //string applicationPath = "../";//HttpContext.Current.Request.ApplicationPath;
            //string applicationPath = HttpContext.Current.Request.FilePath;// "/Trade/Platform/RechargeManualPlatform.aspx"
            //applicationPath = VistorUtils.GetUrlPrefix(applicationPath);
            string css = applicationPath + "Images/ymPrompt/ymPrompt.css";
            string newCSS = "<link type=\"text/css\" rel=\"stylesheet\" href='" + css + "'/>";
            string js = applicationPath + "Scripts/ymPrompt.js";
            string jscommom = applicationPath + "Scripts/commom.js";/
            if (IsMasterPage)
            {
                writer.Write(tempWriter.ToString());
            }
            else
            {
                string css = "/images/ymPrompt/ymPrompt.css";
                string newCSS = "<link type=\"text/css\" rel=\"stylesheet\" href='" + css + "'/>";
                string js = "/js/ymPrompt.js";
                string jscommom = "/js/commom.js";
                string newjs = "<script type=\"text/javascript\" src=\"" + js + "\"></script><script type=\"text/javascript\" src=\"" + jscommom + "\"></script>";
                string newstr = newCSS + newjs + "</HEAD>";
                writer.Write(Regex.Replace(tempWriter.ToString(), "</HEAD>", newstr, RegexOptions.IgnoreCase));
                writer.Write("<HEAD></HEAD>");
            }
        }*/
        #endregion
        #region 登陆验证
        /// <summary>
        /// 判断用户是否已登陆
        /// </summary>
        /// <returns></returns>
        protected bool IsLogin()
        {
            //验证用户登陆的方式
            //1. 签名Cookie
            //2. Session
            //3. 自定义缓存
            //4. 每次访问页面,再通过数据库查询
            //5. ....
            //自定义验证方式
            //通过cookie实现跨页面访问?
            // 用户身份验证
            if (CurUserInfo != null)
                return true;
            HttpContext context = HttpContext.Current;
            HttpCookie cookie = context.Request.Cookies["CrazyTalk_tg"];
            //取出唯一识别码
            //根据唯一识别码,获取用户信息集
            if (cookie == null || string.IsNullOrWhiteSpace(CookieHelper.GetCookieValue("CrazyTalk_tg", "_ug")))
                return false;
            string userId = CookieHelper.GetCookieValue("CrazyTalk_tg", "_ug");
            string sign = CookieHelper.GetCookieValue("CrazyTalk_tg", "Sign");
            //登陆时生成一个唯一编号guid，并记录在数据库（缓存）
            //可以再加多一些key，增加破解难度
            if (VistorUtils.VerifySign(string.Format("{0}tx{1}", userId, SecurityConfig.GetConfig().PasswordKey), sign))
            {
                //取得会话数据
                //UserSession session = BizModule<UserSessionBLL>.CreateInstance.GetModelByCache("/User/UserSession/" + userToken);
                //获取用户信息
                UserInfoBLL bll = UserInfoBLL.Instance;
                UserInfo userInfo = bll.GetModelByCache(userId);
                if (userInfo == null)
                {
                    return false;
                }
                CurUserInfo = userInfo;
                //子账号的适配                
                if (bll.IsChildAccount2(CurUserInfo.RoleId))
                {
                    AdaptUserId = CurUserInfo.ParentId;
                    AdaptRoleId = Convert.ToInt32(bll.GetModelByCache(CurUserInfo.ParentId).RoleId);
                }
                else
                {
                    AdaptUserId = CurUserInfo.UserId;
                    AdaptRoleId = CurUserInfo.RoleId;
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
        /// <summary>
        /// 类名:public bool IsAdmin
        /// 作者:张扬波
        /// QQ: :279883326
        /// 完成日期:2012年3月14日
        /// 功能描述:是否是管理员登录,Role=0
        /// -----------------第一次修改-----------------
        /// 修改作者:
        /// QQ:
        /// 修改日期:
        /// 修改描述:
        /// </summary>
        public bool IsAdmin
        {
            get
            {
                //return false;
                return CurUserInfo.RoleId == (int)ERole.Root;
            }
        }
        private List<Permission> _currUserPermissionList;
        /// <summary>
        /// 当前用户的权限列表
        /// </summary>
        public List<Permission> CurrUserPermissionList
        {
            get
            {
                if (_currUserPermissionList == null)
                    _currUserPermissionList = PermissionBLL.Instance.GetPermissionListByCache(CurUserInfo.UserId, CurUserInfo.RoleId);
                return _currUserPermissionList;
            }
            set { _currUserPermissionList = value; }
        }
    }
    public class PermissPage : UserPage
    {
        public PermissPage()
        {
        }
        private static readonly List<int> unCheckMenuIDList;
        static PermissPage()
        {
            unCheckMenuIDList = new List<int>();
            unCheckMenuIDList.AddRange(new int[] 
            {
                -1,               
                101 //个人资料
            });
        }
        protected override void OnInit(EventArgs e)
        {
            int status = (int)UserStatusType.审核中;
            int status1 = (int)UserStatusType.申请绑定网吧审核中;
            int status2 = (int)UserStatusType.退出网吧绑定审核中;
            int status3 = (int)UserStatusType.退出网吧冻结;
            bool flg = false;
            for (int i = 0; i < MenuIdList.Count; i++)
            {
                if (unCheckMenuIDList.Contains(MenuIdList[i]) == true)
                {
                    flg = true;
                    break;
                }
            }
            if (flg == false
                && CurUserInfo.UserStatus > 0
                && ((status & CurUserInfo.UserStatus) == status
               || (status1 & CurUserInfo.UserStatus) == status1
               || (status2 & CurUserInfo.UserStatus) == status2
               || (status3 & CurUserInfo.UserStatus) == status3
               ))
            {
                //string wstr = GetWrongLink(CurUserInfo);
                //WebKits.PageRender("用户未审核通过，不能当前操作，请联系上家审核！", true, RequestHelper.GetUrl(), false, wstr);              
                MessageBox_On_The_Lower_Depths("info", "抱歉！您的状态为审核中，暂时不能进入系统。，", "/index.html", 2);
                HttpContext.Current.Response.End();
            }
            /**/
            InHasPermission();
            base.OnInit(e);
        }
        /// <summary>
        /// 类名:private string GetWrongLink(UserInfo userInfo)
        /// 作者:于殿磊
        /// QQ: :806591957
        /// 完成日期:2012年8月29日
        /// 功能描述:根据角色生成完善信息的链接
        /// -----------------第一次修改-----------------
        /// 修改作者:
        /// QQ:
        /// 修改日期:
        /// 修改描述:
        /// </summary>
        private string GetWrongLink(UserInfo userInfo)
        {
            string result = "";
            if (userInfo == null || string.IsNullOrWhiteSpace(userInfo.UserId))
            {
                return result;
            }
            result = "";
            if ((RoleType)userInfo.RoleId == RoleType.连锁加盟网吧 || (RoleType)userInfo.RoleId == RoleType.直营店
                || (RoleType)userInfo.RoleId == RoleType.独立网吧 || (RoleType)userInfo.RoleId == RoleType.连锁公司)
            {
                int sign = 0;
                result += "<li>请完善以下信息：<ul style='font-size:120%;'>";
                result += "</ul></li>";
                if (sign == 0)
                {
                    result = "";
                }
            }
            //if ((RoleType)userInfo.RoleId == RoleType.连锁公司 || (RoleType)userInfo.RoleId == RoleType.推广员)
            //{
            //    //判断有无银行卡信息
            //    BankInfos bmodel = BizModule<BankInfosBLL>.CreateInstance.GetModel(userInfo.UserId);
            //    if (bmodel == null || string.IsNullOrWhiteSpace(bmodel.CardID))
            //    {
            //        result += "<li>请完善以下信息：<ul style='font-size:120%;'><li><a href='../User/EditBankInfos.aspx'>完善银行卡信息</a></li><ul></li> ";
            //    }
            //    else
            //    {
            //        result = "";
            //    }
            //}
            return result;
        }
        /// <summary>
        /// 类名:private void HasRole()
        /// 作者:张扬波
        /// QQ: :279883326
        /// 完成日期:2012年3月14日
        /// 功能描述:进入页面权限判断，在UserPage构造函数中调用
        /// -----------------第一次修改-----------------
        /// 修改作者:王胜国
        /// QQ:
        /// 修改日期:2012-10-24
        /// 修改描述:修改验证代码
        /// </summary>
        protected virtual void InHasPermission()
        {
            //if (MenuID == -1)
            //    return;
            //if (CurrUserPermissionList == null || !(CurrUserPermissionList.Where(o => o.MenuID == MenuID).Count() > 0))
            //{
            //    //AlertAndGo("没有权限", HttpContext.Current.Request.UrlReferrer.ToString());
            //    MessageBox_On_The_Lower_Depths("wrong", "非常抱歉，访问错误：没有授权的访问。", "/default.aspx", 3);
            //    Response.End();
            //}
            if (MenuIdList.Count() == 1 && MenuIdList[0] == -1)
                return;
            if (CurrUserPermissionList == null)
            {
                MessageBox_On_The_Lower_Depths("wrong", "非常抱歉，访问错误：没有授权的访问。", "/default.aspx", 3);
                Response.End();
            }
            bool flg = false;
            for (int i = 0; i < MenuIdList.Count(); i++)
            {
                if (CurrUserPermissionList.Where(o => o.MenuID == MenuIdList[i]).Count() > 0)
                {
                    flg = true;
                    break;
                }
            }
            if (flg == false)
            {
                MessageBox_On_The_Lower_Depths("wrong", "非常抱歉，访问错误：没有授权的访问。", "/default.aspx", 3);
                Response.End();
            }
        }
        /// <summary>
        /// 根据角色，获取用户上级网吧连锁公司级的ID
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string GetParent(UserInfo user)
        {
            return "";
            /*
            switch ((RoleType)user.RoleId)
            {
                case RoleType.连锁加盟网吧:
                case RoleType.直营店:
                case RoleType.连锁网吧公司财务员:
                case RoleType.连锁网吧公司管理员:
                case RoleType.连锁公司客服:
                    return user.ParentId;
                case RoleType.网吧收银员:
                case RoleType.网吧管理员:
                case RoleType.网吧客服:
                    Model.UserInfo umod = GetModelById(user.ParentId);
                    return (umod != null ? umod.ParentId : "");
                case RoleType.推广员:
                    if (user.ParentId.ToLower() == "root")
                    {
                        return "root";
                    }
                    else
                    {
                        Model.UserInfo umod2 = GetModelById(user.ParentId);
                        return (umod2 != null ? umod2.ParentId : "");
                    }
                default:
                    return "";
            }*/
        }
        /// <summary>
        /// 通过id找到model
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static UserInfo GetModelById(string uid)
        {
            return UserInfoBLL.Instance.GetModelByCache(uid);
        }
        /// <summary>
        /// 将来信息提示页面UI优化可以统一在此进行编写
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="errcode"></param>
        public void WriteEnd(string msg, EErrorCode errcode)
        {
            //HttpContext.Current.Response.Write(string.Format("{0}！Code={1}", msg, (int)errcode));
            //HttpContext.Current.Response.End();
            string message = string.Format("{0}！Code={1}", msg, (int)errcode);
            WebKits.PageRender(message, false, RequestHelper.GetUrl(), false, "");
        }
        /// <summary>
        /// 类名:protected virtual void CheckPermit()
        /// 作者:张扬波
        /// QQ: :279883326
        /// 完成日期:2012年3月14日
        /// 功能描述:子类重写此方法，如隐藏页面按钮
        /// -----------------第一次修改-----------------
        /// 修改作者:
        /// QQ:
        /// 修改日期:
        /// 修改描述:
        /// </summary>
        protected virtual void CheckPermit()
        {
        }
        private List<int> _menuidlist;
        /// <summary>
        /// 适配一个页面挂了多个菜单ID
        /// </summary>
        public List<int> MenuIdList
        {
            get
            {
                return _menuidlist;
            }
            set
            {
                _menuidlist = value;
            }
        }
        private int _menuid = -1;
        /// <summary>
        /// 编号为-1的，默认任何用户都拥有权限
        /// </summary>
        public int MenuID
        {
            get { return _menuid; }
            set
            {
                _menuid = value;
                if (_menuidlist == null)
                {
                    _menuidlist = new List<int>();
                    _menuidlist.Add(value);
                }
            }
        }
        private int _menuidForExpand = -1;
        /// <summary>
        /// 控制菜单展开变量，在每个页面中都要赋值菜单ID
        /// </summary>
        public int MenuIDForExpand
        {
            get { return _menuidForExpand; }
            set { _menuidForExpand = value; }
        }
    }
}
